package vip.pwztx.api.util.song;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import vip.pwztx.api.entity.song.Song;

import java.util.ArrayList;
import java.util.List;

/**
 * 歌曲工具类
 *
 * @author zhoubaohua
 * @date 2019/10/22
 */
public class SongUtil {
    public static List<Song> getSongList(JSONArray jsonArray) {
        List<Song> list = new ArrayList<>();
        jsonArray.forEach(obj -> {
            Song song = new Song();
            JSONObject jsonObject = JSONObject.parseObject(JSONArray.parseArray(obj.toString()).get(0).toString());
            if (jsonObject.containsKey("rateFormats")) {
                List<String> qualities = new ArrayList<>();
                JSONArray rateFormats = jsonObject.getJSONArray("rateFormats");
                rateFormats.forEach(rateFormat -> qualities.add(JSONObject.parseObject(rateFormat.toString()).getString("formatType")));
                qualities.remove("LQ");
                song.setQualities(qualities);
                list.add(song);
            }
            song.setContentId(jsonObject.getString("contentId"));
            song.setCopyrightId(jsonObject.getString("copyrightId"));
            song.setSongName(jsonObject.getString("name"));
            JSONArray singers = jsonObject.getJSONArray("singers");
            StringBuilder singersName = new StringBuilder();
            if (singers.size() == 1) {
                singersName.append(JSONObject.parseObject(singers.get(0).toString()).getString("name"));
            } else {
                singersName.append(JSONObject.parseObject(singers.get(0).toString()).getString("name"));
                for (int i = 0; i < singers.size(); i++) {
                    singersName.append("&").append(JSONObject.parseObject(singers.get(0).toString()).getString("name"));
                }
            }
            song.setSingerName(singersName.toString());
            if (jsonObject.containsKey("albums")) {
                song.setAlbumName(JSONObject.parseObject(jsonObject.getJSONArray("albums").get(0).toString()).getString("name"));
            } else {
                song.setAlbumName("");
            }
            song.setLyricUrl(jsonObject.getString("lyricUrl"));
        });
        return list;
    }

    /**
     * 将格式转换为后缀名
     *
     * @param formatType 格式
     * @return 后缀名
     */
    public static String convertFormatType(String formatType) {
        if (StringUtils.equals("SQ", formatType)) {
            return "flac";
        }
        return "mp3";
    }
}
